import axios from 'axios'

export class TranslationService {
  private static cache: Record<string, Record<string, string>> = {}
  private static loadingElement: HTMLDivElement | null = null

  private static showLoading() {
    if (!this.loadingElement) {
      this.loadingElement = document.createElement('div')
      this.loadingElement.className = 'translation-loading'
      this.loadingElement.innerHTML = `
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <span>正在翻译...</span>
        </div>
      `
      document.body.appendChild(this.loadingElement)
    }
    this.loadingElement.style.display = 'flex'
  }

  private static hideLoading() {
    if (this.loadingElement) {
      this.loadingElement.style.display = 'none'
    }
  }

  static async translateText(text: string, targetLang: string): Promise<string> {
    // 检查缓存
    if (this.cache[targetLang]?.[text]) {
      return this.cache[targetLang][text]
    }

    try {
      const response = await axios.post('http://localhost:3001/api/translate', {
        text,
        target: targetLang
      })

      const translatedText = response.data.translatedText

      // 更新缓存
      if (!this.cache[targetLang]) {
        this.cache[targetLang] = {}
      }
      this.cache[targetLang][text] = translatedText

      return translatedText
    } catch (error) {
      console.error('翻译失败:', error)
      return text
    }
  }
  
  static async translateElement(element: HTMLElement, targetLang: string) {
    try {
      this.showLoading()
      const walker = document.createTreeWalker(
        element,
        NodeFilter.SHOW_TEXT,
        null
      )

      let node
      while ((node = walker.nextNode())) {
        const text = node.textContent?.trim()
        if (text && text.length > 0) {
          const translatedText = await this.translateText(text, targetLang)
          if (translatedText !== text) {
            node.textContent = node.textContent?.replace(text, translatedText) ?? null
          }
        }
      }
    } finally {
      this.hideLoading()
    }
  }

  static async translateBatch(
    texts: string[],
    targetLang: string,
    source?: string
  ): Promise<Record<string, string>> {
    try {
      this.showLoading()

      // 检查缓存，收集未缓存的文本
      const result: Record<string, string> = {}
      const uncachedTexts: string[] = []

      texts.forEach(text => {
        if (this.cache[targetLang]?.[text]) {
          result[text] = this.cache[targetLang][text]
        } else {
          uncachedTexts.push(text)
        }
      })

      if (uncachedTexts.length > 0) {
        const response = await axios.post('http://localhost:3001/api/translate-batch', {
          texts: uncachedTexts,
          target: targetLang,
          source
        })

        // 更新缓存和结果
        if (!this.cache[targetLang]) {
          this.cache[targetLang] = {}
        }

        response.data.translations.forEach((item: { key: string; translation: string }) => {
          this.cache[targetLang][item.key] = item.translation
          result[item.key] = item.translation
        })
      }

      return result
    } catch (error) {
      console.error('批量翻译请求失败:', error)
      // 翻译失败时返回原文
      const result: Record<string, string> = {}
      texts.forEach(text => {
        result[text] = text
      })
      return result
    } finally {
      this.hideLoading()
    }
  }

  static async checkTranslationService(): Promise<boolean> {
    try {
      const response = await axios.get('http://localhost:3001/health')
      return response.status === 200
    } catch (error) {
      console.error('翻译服务不可用:', error)
      return false
    }
  }
}

// 添加到全局样式
const style = document.createElement('style')
style.textContent = `
.translation-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: none;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  background: #2d2d2d;
  padding: 20px 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 15px;
  color: #fff;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid #404040;
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
`
document.head.appendChild(style)